/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.fragment;

import java.util.List;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.NearestRoutesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.RunStopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TaskIntentHolder;
import lt.marsrutai.mobile.android.adapter.NextArrivalTimeAdapter;
import lt.marsrutai.mobile.android.fragment.task.GetArrivalTimesTaskFragment;
import lt.marsrutai.mobile.android.fragment.task.TaskFragment;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.ArrivalTime;
import lt.marsrutai.mobile.android.task.GetArrivalTimesTask;
import lt.marsrutai.mobile.android.task.GetStopsTask;
import lt.marsrutai.mobile.android.util.HourMinuteFormat;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockListFragment;

public class NextArrivalTimesFragment extends SherlockListFragment {
    
    private static final String GET_ARRIVAL_TIMES_TASK_FRAGMENT_TAG = "getArrivalTimesTaskFragment";

    private FragmentManager fragmentManager;
    private ActivityManager manager;

    private List<ArrivalTime> nextArrivalTimes;
    private NextArrivalTimeAdapter adapter;

    private String scopeFolder;
    private String stopName;
    private String stopId;
    
    private BroadcastReceiver arrivalTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TaskIntentHolder holder = new TaskIntentHolder(intent);
            nextArrivalTimes = holder.getListResult();

            if (holder.getStatus() == GetStopsTask.RESULT_NOT_RESOLVED) {
                manager.runOnUiThread(manager.errorRes);
            }
            else {
                fillAdapter();
                manager.dismissDownloadLoadingBar();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        ((TextView) view.findViewById(android.R.id.empty)).setText(R.string.next_arrivals_not_found);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fragmentManager = getFragmentManager();
        manager = new ActivityManager(getActivity());
        manager.showDownloadLoadingBar();

        receiveItemData();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(arrivalTimeReceiver);
    }
    
    @Override
    public void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(arrivalTimeReceiver, new IntentFilter(GetArrivalTimesTask.BROADCAST_ACTION));

        if (nextArrivalTimes == null) {
            // Check whether the worker fragment has been retained
            TaskFragment<?, ?, ?> taskFragment = (TaskFragment<?, ?, ?>) fragmentManager.findFragmentByTag(GET_ARRIVAL_TIMES_TASK_FRAGMENT_TAG);
    
            // Start downloading only if we don't have any scopes, and task fragments has not been retained
            if (!TaskFragment.isActive(taskFragment)) {
                downloadData();
            }
        }
        else {
            // already have all the data - display it
            fillAdapter();
            manager.dismissDownloadLoadingBar();
        }
    }

    protected void downloadData() {
        TaskFragment.download(fragmentManager, 
                GetArrivalTimesTaskFragment.class, GET_ARRIVAL_TIMES_TASK_FRAGMENT_TAG,
                new GetArrivalTimesTask.Criteria[] {new GetArrivalTimesTask.Criteria(scopeFolder, stopName, stopId, null, 1440, 100)});
    }

    private void fillAdapter() {
        adapter = new NextArrivalTimeAdapter(getActivity(), scopeFolder);
        adapter.setArrivalTimes(nextArrivalTimes);
        
        setListAdapter(adapter);
    }
    
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        sendItemData(position);
    }

    public void receiveItemData() {
        NearestRoutesIntentHolder intentHolder = new NearestRoutesIntentHolder(getArguments());
        scopeFolder = intentHolder.getScopeFolder();
        stopName = intentHolder.getStopName();
        stopId = intentHolder.getStopId();
    }
    
    public void sendItemData(int i) {
        ArrivalTime time = nextArrivalTimes.get(i);               
        RunStopsIntentHolder intentHolder = new RunStopsIntentHolder(getActivity());
                       
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScopeName(null);        
        intentHolder.setTransportId(time.getTransportId());        
        intentHolder.setScheduleId(time.getScheduleId());
        intentHolder.setScheduleName(time.getScheduleName());
        intentHolder.setScheduleTrackName(null);
        intentHolder.setTrackId(time.getTrackId());
        intentHolder.setTrackName(null);
        intentHolder.setStopId(time.getStopId());
        intentHolder.setStopName(time.getStopName());
        intentHolder.setStopDirectionName(time.getStopDirectionName());                
        intentHolder.setRunId(time.getRunId());
        intentHolder.setScheduledTime(HourMinuteFormat.format(time.getScheduledTime()));
        
        startActivity(intentHolder.getIntent());
    }

}
